import SockJs from 'sockjs-client/dist/sockjs.min.js';
import Stomp from 'stompjs';
import { useUserInfo } from '/@/stores/userInfo';
import { Session } from '/@/utils/storage';
//token信息
const token = computed(() => Session.getToken());
//租户id
const tenant = computed(() => Session.getTenant());
//用户信息
const userInfo = computed(() => useUserInfo()?.userInfos);

//头部信息
const headers = computed(() => {
	return {
		Authorization: 'Bearer ' + token.value,
		tenantId: tenant.value,
		login: userInfo.value?.user.username,
		passcode: userInfo.value?.user.password,
		simpUser: userInfo.value?.user.username 
	};
});
// const headers = ref({});
/**
 * 持久化存储websocket列表
 */
export const useWebsocket = defineStore('websocket', {
	state: () => ({
		webSocket: ref(null) as any as WebSocket, // webSocket实例
		stompClient: ref(null) as any as Stomp.Client,
		lockReconnect: false, // 重连锁，避免多次重连
		enableReconnect: true, // 是否开启重连机制
		maxReconnect: 6, // 最大重连次数， -1 标识无限重连
		reconnectTime: 0, // 重连尝试次数
		heartbeat: {
			interval: 30 * 1000, // 心跳间隔时间
			timeout: 10 * 1000, // 响应超时时间
			pingTimeoutObj: ref(), // 延时发送心跳的定时器
			pongTimeoutObj: ref(), // 接收心跳响应的定时器
			pingMessage: JSON.stringify({ type: 'ping' }), // 心跳请求信息
		},
		websocketMap: new Map(), // websocket连接映射
		subscribeList: [] as string[], // 订阅列表
	}),
	actions: {
		/**
		 * 初始化WebSocket连接
		 *
		 * @param url WebSocket服务器的URL
		 * @param successCallback 连接成功时的回调函数
		 * @param errorCallback 连接失败时的回调函数
		 */
		init(url: string, successCallback: Function, errorCallback: Function): void {
			if (this.stompClient && this.stompClient.connected) {
				return; // 如果STOMP客户端已连接，则直接返回
			}
			if (this.stompClient) {
				// 如果STOMP客户端存在但未连接
				if (this.webSocket.readyState === SockJs.OPEN) {
					// 清除心跳检测定时器
					this.clearTimeoutObj(this.heartbeat);
					// WebSocket已打开，先断开再重连
					this.stompClient.disconnect(() => this.connectWebsocket(url, successCallback, errorCallback),headers.value);
				} else if (this.webSocket.readyState === SockJs.CONNECTING) {
					// WebSocket正在连接中，直接返回
					return;
				}
			}
			// 其他情况，直接连接WebSocket
			this.connectWebsocket(url, successCallback, errorCallback);
		},
		// 初始化STOMP客户端的方法（需要根据实际业务逻辑实现）
		connectWebsocket(url: string, successCallback: Function, errorCallback: Function): void {
			// 如果STOMP客户端已连接，则直接返回
			if (this.stompClient?.connected) return;
			//判断url是否为空
			if (!url) {
				url = import.meta.env.VITE_WEBSOCKET_URL;
			}
			// 创建WebSocket实例
			this.webSocket = new SockJs(url);
			// 创建STOMP客户端实例
			this.stompClient = Stomp.over(this.webSocket);

			// 连接到WebSocket服务器
			this.stompClient.connect(
				headers.value,
				() => {
					// 连接成功的处理逻辑
					console.log(`STOMP connected: ${url}`);
					// 心跳检测初始化
					this.initHeartbeat();
					successCallback(); // 调用成功回调
				},
				(error: any) => {
					// 连接失败的处理逻辑
					console.error(`STOMP connection error: ${error}`);
					// 连接失败时的处理逻辑
					if (this.enableReconnect) {
						this.handleReconnect(url, successCallback, errorCallback);
					} else {
						errorCallback(); // 调用失败回调
					}
				}
			);
		},
		// 订阅主题的方法（示例）
		subscribe(topic: string, callback: Function) {
			if (this.stompClient && this.stompClient.connected) {
				const subId = this.stompClient.subscribe(topic, callback, headers.value);
				this.subscribeList.push(subId);
			}
		},
		subscribeUser(destination: string, callback: Function) {
			if (this.stompClient && this.stompClient.connected) {
				const userName = useUserInfo()?.userInfos?.userName;
				const des =
					destination.substring(0, destination.indexOf('/', 2)) +
					'/' +
					userName +
					destination.substring(destination.indexOf('/', 2), destination.length);
				this.subscribe(des, callback);
			}
		},
		// 取消订阅主题的方法（示例）
		unsubscribe(subId: string) {
			if (this.stompClient && this.stompClient.connected) {
				if (subId && subId !== undefined && subId !== '') {
					this.stompClient.unsubscribe(subId);
					const index = this.subscribeList.indexOf(subId);
					if (index !== -1) {
						this.subscribeList.splice(index, 1);
					}
				} else {
					this.subscribeList.forEach((item) => {
						this.stompClient.unsubscribe(item);
					});
					this.subscribeList = [];
				}
			}
		},
		// 发送消息的方法（示例）
		send(destination: string, message: string) {
			if (this.stompClient && this.stompClient.connected) {
				this.stompClient.send(destination, headers.value, message);
			}
		},
		// 断开连接的方法（示例）
		disconnect(callback: Function) {
			if (this.stompClient && this.stompClient.connected) {
				this.stompClient.disconnect(callback,headers.value);
			}
		},

		// 检查连接状态的方法（示例）
		checkConnected() {
			return this.stompClient && this.stompClient.connected;
		},
		// 关闭WebSocket连接的方法（示例）
		close(callback: Function) {
			if (this.webSocket) {
				this.webSocket.close();
			}
			if (this.stompClient) {
				this.stompClient.disconnect(callback,headers.value);
			}
		},

		// 心跳检测初始化方法（示例）
		initHeartbeat() {
			// 设置心跳间隔
			this.clearTimeoutObj(this.heartbeat); // 清除可能存在的旧定时器
			this.heartbeat.pingTimeoutObj = setTimeout(() => {
				// 发送心跳请求
				if (this.webSocket.readyState === SockJs.OPEN) {
					this.webSocket.send(this.heartbeat.pingMessage);
					this.heartbeat.pongTimeoutObj = setTimeout(() => {
						// 心跳响应超时，关闭WebSocket连接
						this.close();
					}, this.heartbeat.timeout);
				}
			}, this.heartbeat.interval);
		},
		/**
		 * 清空定时器
		 */
		clearTimeoutObj(heartbeat: any): void {
			this.heartbeat.pingTimeoutObj && clearTimeout(this.heartbeat.pingTimeoutObj);
			this.heartbeat.pongTimeoutObj && clearTimeout(this.heartbeat.pongTimeoutObj);
		},
		// 处理重连逻辑的方法（示例）
		handleReconnect(url: string, successCallback: Function, errorCallback: Function) {
			if (this.lockReconnect || (this.maxReconnect !== -1 && this.reconnectTime > this.maxReconnect)) {
				return;
			}
			this.lockReconnect = true;
			setTimeout(() => {
				this.init(url, successCallback, errorCallback);
				this.reconnectTime++;
				this.lockReconnect = false;
			}, 5000); // 重连间隔，可根据需要调整
		},
	},
});
